package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.lostAndFound.LostAndFoundAddRequest;
import com.SmartCampus.system.model.dto.lostAndFound.LostAndFoundQueryRequest;
import com.SmartCampus.system.model.dto.lostAndFound.LostAndFoundUpdateRequest;
import com.SmartCampus.system.model.entity.Lostandfound;
import com.SmartCampus.system.model.vo.LostandfoundVO;
import com.SmartCampus.system.service.LostandfoundService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 失物招领接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/lost")
@Slf4j
@Api(tags = "失物招领接口")
public class LostController {

    @Resource
    private LostandfoundService lostandfoundService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建失物招领
     *
     * @param lostAndFoundAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建失物招领")
    public BaseResponse<Long> addLost(@RequestBody LostAndFoundAddRequest lostAndFoundAddRequest, HttpServletRequest request) {
        if (lostAndFoundAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Lostandfound lost = new Lostandfound();
        BeanUtils.copyProperties(lostAndFoundAddRequest, lost);
        lost.setUserId(userService.getLoginUser(request).getId());
        lost.setStatus("lost");
        lost.setPostDate(new Date());
        boolean result = lostandfoundService.save(lost);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(lost.getId());
    }

    /**
     * 删除失物招领（仅管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除失物招领（仅管理员）")
    public BaseResponse<Boolean> deleteLost(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = lostandfoundService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新失物招领
     *
     * @param lostAndFoundUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新失物招领")
    public BaseResponse<Boolean> updateLost(@RequestBody LostAndFoundUpdateRequest lostAndFoundUpdateRequest, HttpServletRequest request) {
        if (lostAndFoundUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        QueryWrapper<Lostandfound> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", lostAndFoundUpdateRequest.getId());
        Lostandfound oldLost = lostandfoundService.getOne(queryWrapper);
        Long userId = userService.getLoginUser(request).getId();
        if (userId != oldLost.getUserId()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        if (lostAndFoundUpdateRequest.getTitle() == null || lostAndFoundUpdateRequest.getTitle().equals("")) {
            lostAndFoundUpdateRequest.setTitle(oldLost.getTitle());
        }
        if (lostAndFoundUpdateRequest.getDescription() == null || lostAndFoundUpdateRequest.getDescription().equals("")) {
            lostAndFoundUpdateRequest.setDescription(oldLost.getDescription());
        }
        if (lostAndFoundUpdateRequest.getLocation() == null || lostAndFoundUpdateRequest.getLocation().equals("")) {
            lostAndFoundUpdateRequest.setLocation(oldLost.getLocation());
        }
        if (lostAndFoundUpdateRequest.getContact() == null || lostAndFoundUpdateRequest.getContact().equals("")) {
            lostAndFoundUpdateRequest.setContact(oldLost.getContact());
        }
        if (lostAndFoundUpdateRequest.getStatus() == null || lostAndFoundUpdateRequest.getStatus().equals("")) {
            lostAndFoundUpdateRequest.setStatus((String) oldLost.getStatus());
        }
        BeanUtils.copyProperties(lostAndFoundUpdateRequest, oldLost);
        boolean result = lostandfoundService.updateById(oldLost);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取失物招领列表
     *
     * @param lostAndFoundQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "分页获取失物招领列表")
    public BaseResponse<Page<LostandfoundVO>> getLostByAll(@RequestBody LostAndFoundQueryRequest lostAndFoundQueryRequest) {
        long current = lostAndFoundQueryRequest.getCurrent() == 0 ? 1 : lostAndFoundQueryRequest.getCurrent();
        long size = lostAndFoundQueryRequest.getPageSize() == 0 ? 10 : lostAndFoundQueryRequest.getPageSize();
        Page<LostandfoundVO> page = new Page<>(current, size);
        Page<LostandfoundVO> clazzPage = lostandfoundService.getLostByAll(page, lostAndFoundQueryRequest);
        if (clazzPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(clazzPage);
    }

    /**
     * 分页获取用户发布的失物招领列表
     *
     * @param lostAndFoundQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/my")
    @ApiOperation(value = "分页获取用户发布的失物招领列表")
    public BaseResponse<Page<LostandfoundVO>> getLostByMy(@RequestBody LostAndFoundQueryRequest lostAndFoundQueryRequest, HttpServletRequest request) {
        if (lostAndFoundQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userService.getLoginUser(request).getId();
        long current = lostAndFoundQueryRequest.getCurrent() == 0 ? 1 : lostAndFoundQueryRequest.getCurrent();
        long size = lostAndFoundQueryRequest.getPageSize() == 0 ? 10 : lostAndFoundQueryRequest.getPageSize();

        Page<LostandfoundVO> page = new Page<>(current, size);
        Page<LostandfoundVO> clazzPage = lostandfoundService.getLostByMy(page, lostAndFoundQueryRequest, userId);
        if (clazzPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(clazzPage);
    }

    // endregion
}
